import React, { useEffect,useState } from 'react';
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, TextField,  Button, Snackbar, Checkbox } from '@material-ui/core';
import api from '../../api.js';
import "./table.css";
const fetchAddress="/audit";
const tableInfo=["действие","сущность","имя сущности","дата","Пользователь"];
const AuditTable = () => {

  const fetchData= async ()=>{
    const responce = await api.get(fetchAddress);
    return responce.data;
  }
const [data, setData] = useState([]);
useEffect(() => {
    fetchData()
      .then(res => {setData(res);})
      .catch(error => {console.error(error);});
  }, []);
  const [searchTerm, setSearchTerm] = useState('');
  const [sortedField, setSortedField] = useState(null);
  const [sortDirection, setSortDirection] = useState('asc');
  const handleFilter = (field) =>{
  
    const filteredData =  data.map(item => {let res=false;
      for(const [key, value] of Object.entries(item)){
          if(value!=null){
            res|=value.toString().toLowerCase().includes(field.toLowerCase());
          }}
    item.hidden=!res;
  return item;
}
    
    );
    setSearchTerm(field);
    setData(filteredData);
  }
  const handleSort = (field) => {
    let sd=sortDirection === 'asc' ? 'desc' : 'asc';
    if (field === sortedField) {
      setSortDirection(sd);
    } else {
      setSortedField(field);
      setSortDirection('asc');
    }
    const sortedData = field ? data.sort((a, b) => {
      const compareValue = a[field] > b[field] ? 1 : -1;
      return sd === 'asc' ? compareValue : -compareValue;
    }) : data;
    setData(sortedData);
  };

  const getRows=()=>{
   let arr=tableInfo.map((i,e)=><TableCell className='tableHead' key ={e} onClick={() => handleSort(i)}>{i}</TableCell>)
   return arr;
  }
  const createRow=(row)=>{
    let res=[];
    for(const [key, value] of Object.entries(row)){
        res.push(<TableCell key={key}>{value}</TableCell>);
    }
    return res;
  }

  return (
    <TableContainer component={Paper}>
      <div className='main-tools'>
            <div>
            <TextField
                label="Search"
                value={searchTerm}
                onChange={(e) => handleFilter(e.target.value)}
              />
              </div>
        </div>
      <Table>
        <TableHead  className='tableHeadRow'>
          <TableRow >   
            {getRows()}
          </TableRow>
        </TableHead>
        <TableBody className='table-body'>
          {data.map((row,i) => (
            <TableRow className='row' key={i}>
              {
                
              createRow(row)}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
};

export default AuditTable;